﻿using MySql.Data.MySqlClient;
using RantopadService.Business;
using RantopadService.Conn;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace RantopadService.ClientWeb
{
    public partial class ForgetPSW : System.Web.UI.Page
    {
        string lspass = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Button1.Attributes.Add("onclick", "javascript:return checkAll();");
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            
            //首先判断该email是否存在   
            string sql = "select * from rantopad.user where  email='" + email.Text.Trim() + "' ";
            DataTable dt = new DataTable();
            //dt = new SQLTool().dataTable(sql);   
            var myconnection = MyMySqlHelper.GetConn();
            myconnection.Open();
            var dataAdapter = new MySqlDataAdapter(sql, myconnection);
            
            dataAdapter.Fill(dt);
            myconnection.Close();
            if (dt.Rows.Count < 1)
            {  
                Response.Write("<script>alert('Email地址错误！，请重新填写后再试。');</script>");
            }
            else
            {
                addResetPSW(email.Text.Trim());
    
            }
        }

        private int addResetPSW(string email)
        {
            int count = 0;var myconnection = MyMySqlHelper.GetConn();
                myconnection.Open();
            try
            {
                DateTime now = DateTime.Now;
                string mysql = "insert into `resetpsw` (`EMAIL`, `TM`, `EKEY`) VALUES ('{0}', '{1}', '{2}') ";
                mysql = string.Format(mysql, email, DateTime.Now.ToString(), "email=" + CodeBusiness.Encode(email) + "&tm=" + CodeBusiness.Encode(now.ToString()));
                //创建数据库连接
                
                MySqlCommand mycommand = new MySqlCommand(mysql, myconnection);
                string url;
                url = "http://115.159.69.155/ClientWeb/ResetPSW.aspx?" + "email=" + CodeBusiness.Encode(email) + "&tm=" + CodeBusiness.Encode(now.ToString());
                sendEmail(email,url);
                count = mycommand.ExecuteNonQuery();
                myconnection.Close();
                Response.Write("<script>alert('已发送邮件至" + CodeBusiness.Encode(email) + "，请注意查收。');</script>");
            }
            catch (Exception e)
            {
                myconnection.Close();
                NetLog.WriteTextLog(System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), e.Message.ToString(), DateTime.Now);
                count = 0;
            }


            return count;
        }
        
        public bool sendEmail(string email,string url)
        {

            string Email = "no-reply@rantopad.com";
            string password = "pbNv6HGVeW";
            Encoding EnCode = Encoding.UTF8;
            System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
            Message.From = new MailAddress(Email, "Ranto会员管理中心", EnCode);
            Message.To.Add(new MailAddress(email, "尊敬的用户", EnCode));
            Message.Subject = "Ranto找回密码";
            Message.SubjectEncoding = EnCode;

            StringBuilder MailContent = new StringBuilder();
            MailContent.Append("尊敬的用户：<br/>");
            MailContent.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好！你于");
            MailContent.Append(DateTime.Now.ToLongTimeString());
            MailContent.Append("通过<a href=''>Ranto</a>管理中心审请找回密码。");
            MailContent.Append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;为了安全起见，请用户点击以下链接重设个人密码(该地址24小时内有效)：");
            
            MailContent.Append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='" + url + "'>" + url + "</a>");
            Message.Body = MailContent.ToString();
            Message.BodyEncoding = EnCode;
            Message.IsBodyHtml = true;

            try
            {
                SmtpClient smtp = new SmtpClient("smtp.ym.163.com", 25);
                smtp.Credentials = new NetworkCredential(Email, password);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Send(Message);
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                Message.Dispose();
                //Response.Redirect(url);
                Response.Write("<script>window.opener=null;window.close();</script>");
            }
            return true;
        
 
            //try
            //{
            //    jmail.Message jmessage = new jmail.Message();
            //    jmessage.Charset = "GB2312";
            //    jmessage.From = "xt45@163.com";
            //    // 发信地址    
            //    jmessage.MailServerUserName = "86085005";
            //    //smtp认证用户名(注:如为网易用户,不加要@163.com,只要前面部分即可)   
            //    jmessage.MailServerPassWord = "kingseer";
            //    // smtp论证用户名密码    

            //    jmessage.FromName = "108人力银行";
            //    // 发信人    
            //    jmessage.ReplyTo = "t51@163.com";
            //    // 回复地址    
            //    jmessage.C;//邮件内容为html   
            //    jmessage.Subject = "108人力银行临时密码";

            //    string strbody = "";
            //    strbody += new functions().getInfoXX("t_pagetexts", "p_name", "找回密码邮件反馈-个人", "p_value").Replace("$", name).Replace("@%", lspass);
            //    jmessage.HTMLBody = strbody;
            //    // 邮件标题    
            //    jmessage.AddRecipient(email, "", "");
            //    jmessage.Send("smtp.163.com", false);//发送邮件smtp.163.com   
            //    jmessage.Close();//关闭对象,释放资源   
            //}
            //catch (Exception err)
            //{
            //    Response.Write(err);
            //}
        }
        /// <summary>   
        /// 功能：产生数字和字符混合的随机字符串   
        /// </summary>   
        /// <param name="codecount">字符串的个数</param>   
        /// <returns></returns>   
        private string CreateRandomCode(int codecount)
        {
            // 数字和字符混合字符串   
            string allchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n";
            //分割成数组   
            string[] allchararray = allchar.Split(',');
            string randomcode = "";

            //随机数实例   
            System.Random rand = new System.Random(unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < codecount; i++)
            {
                //获取一个随机数   
                int t = rand.Next(allchararray.Length);
                //合成随机字符串   
                randomcode += allchararray[t];
            }
            return randomcode;
        }
    }
}